package com.gcb.common.utils.huawei;

import com.gcb.common.utils.uuid.UUID;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.ivs.v2.IvsClient;
import com.huaweicloud.sdk.ivs.v2.model.DetectStandardByNameAndIdRequest;
import com.huaweicloud.sdk.ivs.v2.model.DetectStandardByNameAndIdResponse;
import com.huaweicloud.sdk.ivs.v2.model.IvsStandardByNameAndIdRequestBody;
import com.huaweicloud.sdk.ivs.v2.model.IvsStandardByNameAndIdRequestBodyData;
import com.huaweicloud.sdk.ivs.v2.model.Meta;
import com.huaweicloud.sdk.ivs.v2.model.StandardReqDataByNameAndId;
import com.huaweicloud.sdk.ivs.v2.region.IvsRegion;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 华为云 人证核身(三要素：名字，身份证号码，人脸图片)
 */
@Slf4j
public class IvsUtils {
    //公钥
    private static final String AK="UIDUSHFQ310BPT2CGXVA";
    //私钥
    private static final String SK="d9I4pm9qts2CJHAKp5p8GChZrexFI5RpglRcKfQp";

    /**
     * 验证身份
     * name:用户姓名；idNum：用户身份证；file：用户照片地址
     * */
    /**
     *
     * @param name 姓名
     * @param userCode 身份证号
     * @param faceImage 现场人像图像数据，使用base64编码，要求base64编码后大小不超过4M。
     *                  图像各边的像素大小在300到4000之间，支持JPG格式
     * @return 0:请求出现异常
     *         1000:核验成功
     *         2001 认证信息不一致，即姓名与身份证号码不一致
     *         2002 人脸与身份证信息不符
     *         2003 人脸图像质量或格式问题
     *         2004 未检测到人脸或检测到多张人脸
     *         2005 证件照不存在，属于数据源问题（极少出现这种情况）
     *         3001 认证中心数据源无此身份证信息，可能原因是被验证人正在办理户籍迁移，或者被验证人是军人或政要。
     */
    public static int verifyIdentity(String name, String userCode, String faceImage){
        DetectStandardByNameAndIdRequest request = new DetectStandardByNameAndIdRequest();
        IvsStandardByNameAndIdRequestBody requestBody = new IvsStandardByNameAndIdRequestBody();
        Meta meta = new Meta();
        String uuid=UUID.randomUUID().toString();
        meta.setUuid(uuid);
        requestBody.withMeta(meta);
        IvsStandardByNameAndIdRequestBodyData bodyData = new IvsStandardByNameAndIdRequestBodyData();
        List<StandardReqDataByNameAndId> byNameAndIds = new ArrayList<>();
        StandardReqDataByNameAndId byNameAndId = new StandardReqDataByNameAndId();
        byNameAndId.withFaceImage(faceImage);//base64照片
        byNameAndId.withVerificationId(userCode);//"61**********1"
        byNameAndId.withVerificationName(name);//"张三"
        byNameAndIds.add(byNameAndId);
        bodyData.withReqData(byNameAndIds);
        requestBody.withData(bodyData);
        request.withBody(requestBody);

        ICredential credential = getCredential(AK, SK);
        IvsClient client = getClient(credential);
        try {
            DetectStandardByNameAndIdResponse response = client.detectStandardByNameAndId(request);
            log.info(name+userCode+"认证返回的数据："+response.toString());
            return response.getResult().getRespData().get(0).getVerificationCode();
        } catch (ConnectionException e) {
            log.error(e.toString());
        } catch (RequestTimeoutException e) {
            log.error(e.toString());
        } catch (ServiceResponseException e) {
            log.error(e.toString());
        } catch (Exception e){
            log.error(userCode+"认证失败!!!!!!!!!!verifyIdentity:"+e.toString());
        }
        return 0;
    }

    /**
     * 创建Credential凭证
     * @param ak 公钥
     * @param sk 私钥
     * @return
     */
    public static ICredential getCredential(String ak, String sk) {
        return new BasicCredentials()
                .withAk(ak)
                .withSk(sk);
    }

    /**
     * 创建Client并实例化
     * @param auth 凭证
     * @return Client实例
     */
    public static IvsClient getClient(ICredential auth) {
        // 初始化客户端
        return IvsClient.newBuilder()
                .withCredential(auth)
                .withRegion(IvsRegion.CN_NORTH_4) // 选择服务部署区域 IvsRegion.CN_NORTH_4
                .build();
    }
}
